package com.titleevaluation.service;

import com.titleevaluation.entity.Application;
import com.titleevaluation.entity.PersonalInfo;
import com.titleevaluation.repository.ApplicationRepository;
import com.titleevaluation.repository.PersonalInfoRepository;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Optional;

@Service
public class PersonalInfoService {

    private final PersonalInfoRepository personalInfoRepository;
    private final ApplicationRepository applicationRepository;

    public PersonalInfoService(PersonalInfoRepository personalInfoRepository, ApplicationRepository applicationRepository) {
        this.personalInfoRepository = personalInfoRepository;
        this.applicationRepository = applicationRepository;
    }

    public PersonalInfo createOrUpdatePersonalInfo(Long applicationId, PersonalInfo personalInfo) {
        Application application = applicationRepository.findById(applicationId)
                .orElseThrow(() -> new RuntimeException("Application not found"));

        Optional<PersonalInfo> existingInfo = personalInfoRepository.findByApplicationId(applicationId);
        if (existingInfo.isPresent()) {
            PersonalInfo infoToUpdate = existingInfo.get();
            infoToUpdate.setName(personalInfo.getName());
            infoToUpdate.setGender(personalInfo.getGender());
            infoToUpdate.setIdCardNo(personalInfo.getIdCardNo());
            infoToUpdate.setPhoneNumber(personalInfo.getPhoneNumber());
            infoToUpdate.setPoliticalStatus(personalInfo.getPoliticalStatus());
            infoToUpdate.setHighestEducation(personalInfo.getHighestEducation());
            infoToUpdate.setHighestDegree(personalInfo.getHighestDegree());
            infoToUpdate.setGraduationDate(personalInfo.getGraduationDate());
            infoToUpdate.setGraduationSchool(personalInfo.getGraduationSchool());
            infoToUpdate.setMajor(personalInfo.getMajor());
            infoToUpdate.setWorkUnit(personalInfo.getWorkUnit());
            infoToUpdate.setWorkPosition(personalInfo.getWorkPosition());
            infoToUpdate.setTechnicalWorkYears(personalInfo.getTechnicalWorkYears());
            infoToUpdate.setJoinWorkDate(personalInfo.getJoinWorkDate());
            infoToUpdate.setPhotoPath(personalInfo.getPhotoPath());
            infoToUpdate.setUpdatedAt(LocalDateTime.now());
            return personalInfoRepository.save(infoToUpdate);
        } else {
            personalInfo.setApplication(application);
            personalInfo.setCreatedAt(LocalDateTime.now());
            personalInfo.setUpdatedAt(LocalDateTime.now());
            return personalInfoRepository.save(personalInfo);
        }
    }

    public Optional<PersonalInfo> getPersonalInfoByApplicationId(Long applicationId) {
        return personalInfoRepository.findByApplicationId(applicationId);
    }
}

